package com.zhoug.common3.base.webview;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


import com.zhoug.common3.utils.bundle.BundleWrap;

import androidx.annotation.NonNull;

/**
 * WebView页面工具类,用于初始化配置和加载网页
 * @Author 35574
 * @Date 2021/10/25
 * @Description
 */
public class WebPageHelper {
    private WebView webView;
    private BundleWrap config;

    public WebPageHelper(@NonNull WebView webView, Bundle args) {
        this.webView = webView;
        this.config = BundleWrap.with(args);
        WebSettings webSettings = WebViewUtils.settingsConfig(webView);
        if (config != null) {
            webSettings.setJavaScriptEnabled(config.getBoolean(WebPageLauncher.PARAM_JAVASCRIPT_ENABLED, true));
            int defaultFontSize = config.getInt(WebPageLauncher.PARAM_DEFAULT_FONT_SIZE);
            if (defaultFontSize > 0) {
                webSettings.setDefaultFontSize(defaultFontSize);
            }
        }
    }

    public WebPageHelper setWebViewClient(WebViewClient webViewClient) {
        webView.setWebViewClient(webViewClient);
        return this;
    }

    /**
     * 获取标题
     *
     * @return
     */
    public String getTitle() {
        return config.getString(WebPageLauncher.PARAM_TITLE);
    }

    public void load() {
        String contentSource = config.getString(WebPageLauncher.PARAM_CONTENT_SOURCE);
        String url = config.getString(WebPageLauncher.PARAM_URL);
        if (contentSource != null) {
            loadData(contentSource);
        } else if (url != null) {
            loadUrl(url);
        }
    }


    /**
     * 加载网页url
     *
     * @param url
     */
    protected void loadUrl(String url) {
        webView.loadUrl(url);
    }

    /**
     * 加载网页内容
     *
     * @param html
     */
    protected void loadData(String html) {
        webView.loadData(html, WebViewUtils.MIMETYPE_TEXT_HTML, null);
    }

    /**
     * 在{@link Activity#onBackPressed()}中调用
     * @param activity
     */
    public  void onBackPressed( Activity activity) {
        WebViewUtils.onBackPressed(webView,activity);
    }

}
